﻿
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.StsAdmin;
using System.Collections.Specialized;
using Microsoft.SharePoint;
using System.IO;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Administration;

namespace Macaw.Wss3.DependencySpiderSolution
{
    public class StartDependencySpiderStsAdmExtension : ISPStsadmCommand
    {
        #region ISPStsadmCommand Members

        string ISPStsadmCommand.GetHelpMessage(string command)
        {
            StringBuilder message = new StringBuilder();
            message.Append("-url <site>");
            return message.ToString();
        }

        int ISPStsadmCommand.Run(string command, StringDictionary keyValues, out string output)
        {
            if (!keyValues.ContainsKey("url"))
            {
                output = "The \"url\" parameter was not specified.";
                return -1;
            }

            try
            {
                String url = keyValues["url"];

                using (SPSite site = new SPSite(url))
                {
                    SPWebApplication webapp = site.WebApplication;

                    // Make sure the job isn't already registered.
                    foreach (SPJobDefinition oldjob in webapp.JobDefinitions)
                    {
                        if (oldjob.Name == DependencySpiderJobDefinition.JobName + "_now")
                            oldjob.Delete();
                    }


                    #region OneTime Schedule
                    DependencySpiderJobDefinition job = new DependencySpiderJobDefinition(webapp);
                    job.Name += "_now";
                    job.Schedule = new SPOneTimeSchedule(DateTime.Now);
                    job.Update();
                    #endregion                    
                }
            }
            catch (Exception ex)
            {
                output = "Error!\r\n" + ex.ToString();
                return -1;
            }
            output = "Done.";
            return 0;
        }

        #endregion
    }
}
